<template>
	<!-- 行政区域选择器 -->
	<div @click="show=true">
		<u-input readonly :value="text" placeholder="行政区域" border="none"></u-input>
		<u-picker 
			:key="pickerKey"
			:show="show" ref="uPicker" :columns="columns" @confirm="confirm" @change="changeHandler"
			keyName="areaName"
			@cancel="show = false"
			@close="show = false"
		>
		</u-picker>
	</div>
</template>

<script>
	export default {
		props: {
			// 区域编码
			value: String,
			// 所选区域列表
			list: Array,
			// 区域全称
			areaText: String,
		},
		data(){
			return {
				pickerKey: 1,
				show: false,
				columns: [],
				text: null,
			};
		},
		mounted() {
			this.initList();
			this.text = this.areaText;
		},
		methods: {
			// 初始化第一个列表数据
			initList(){
				this.$api.sysArea.list({areaCode: '000000'}).then(({data}) => {
					let list = data;
					console.log("省份：", list);
					this.$set(this.columns, 0, list);
					this.initTreeList(0, list[0]);
					// this.pickerKey = Date.now() + ""; 
				});
			},
			changeHandler(e) {
				console.log("更新选中", e);
				if (!e.index) {
					return;
				}
				let picker = this.$refs.uPicker;
				// 第几列
				let index = e.columnIndex;
				
				if (index === 0) {
					picker.setColumnValues(1, []);
					picker.setColumnValues(2, []);
				}
				
				if (index >= 2) {
					return;
				}
				// 选中值
				let item = e.value[index];
				
				picker.setColumnValues(index + 1, []);
				
				this.initTreeList(index, item);
			},
			/** 
			 * 初始化下级数据
			 * @param {Object} index 当前第几列
			 * @param {Object} item 选中值
			 */
			initTreeList(index, item){
				if (index >= 2) {
					return;
				}
				
				this.$api.sysArea.list({areaCode: item.areaCode}).then(({data}) => {
					let list = data;
					let picker = this.$refs.uPicker;
					// this.$set(this.columns, index + 1, list);
					picker.setColumnValues(index + 1, list);
					if (list && list.length > 0) {
						this.initTreeList(index + 1, list[0]);
					}
				});
			},
			// 回调参数为包含columnIndex、value、values
			confirm(e) {
				console.log('confirm', e);
				let value = e.value;
				let traceVal = value.filter(item=>item);
				console.log("选中：", traceVal);
				if (traceVal.length > 0) {
					let lastVal = traceVal[traceVal.length - 1];
					let text = traceVal.map(item=>item.areaName).join(',');
					this.text = text;
					
					// 发送到父组件
					this.$emit('input', lastVal.areaCode);
					this.$emit('update:areaName', lastVal.areaName);
					this.$emit('update:list', traceVal);
					this.$emit('update:areaText', text);
				}
				this.show = false;
			}
		},
	}
</script>

<style>
</style>
